package mysql

import (
	"fmt"
	"gitee.com/captials-team/ubdframe/src/domain/configstc"
	"gitee.com/captials-team/ubdframe/src/domain/dto/paginate"
	"gitee.com/captials-team/ubdframe/src/domain/interfaces"
	"gitee.com/captials-team/ubdframe/src/domain/models"
	mysqlClients "gitee.com/captials-team/ubdframe/src/infrastructure/clients/mysql"
	"gorm.io/gorm"
)

func NewOrganizeRelateDao(conf configstc.DBConfig) *OrganizeRelateDao {
	return &OrganizeRelateDao{
		DBFacade: NewGormDBFacade[models.OrganizeRelate](mysqlClients.NewGormDB(conf)),
		conf:     conf,
	}
}

type OrganizeRelateDao struct {
	interfaces.DBFacade[models.OrganizeRelate]
	conf configstc.DBConfig
}

func (dao *OrganizeRelateDao) SearchParent(orgId int64, level int) ([]*models.OrganizeRelate, error) {
	list, _, err := dao.DBFacade.Search(&paginate.Pager{
		Page: 1,
		Size: 1000,
	}, func(db *gorm.DB) *gorm.DB {
		if level > 0 {
			db = db.Where("level", level)
		}
		return db.Where("org_id", orgId)
	})
	return list, err
}

func (dao *OrganizeRelateDao) SearchChild(orgId int64, level int) ([]*models.OrganizeRelate, error) {
	list, _, err := dao.DBFacade.Search(&paginate.Pager{
		Page: 1,
		Size: 1000,
	}, func(db *gorm.DB) *gorm.DB {
		if level > 0 {
			db = db.Where("level", level)
		}
		return db.Where("org_parent", orgId)
	})
	return list, err
}

func (dao *OrganizeRelateDao) Clear(orgId int64) (int64, error) {
	return dao.DBFacade.DeleteByScope(func(db *gorm.DB) *gorm.DB {
		return db.Where("org_id", orgId)
	})
}

func (dao *OrganizeRelateDao) SqlForSearchChild(pid int64, level int) string {
	table := new(models.OrganizeRelate).TableName(dao.DB().NamingStrategy)
	sql := fmt.Sprintf("SELECT org_id FROM %s WHERE org_parent=%d", table, pid)
	if level > 0 {
		sql = sql + fmt.Sprintf(" AND level=%d", level)
	}

	return sql
}

func (dao *OrganizeRelateDao) Use(db *gorm.DB) interfaces.ItfOrganizeRelate {
	return &OrganizeRelateDao{
		conf:     dao.conf,
		DBFacade: dao.DBFacade.UseDB(db),
	}
}
